package com.examples.gateway.helper.filter;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.examples.core.req.ExamBaseReq;
import com.examples.core.req.ExamHeader;
import com.examples.gateway.common.CheckState;
import com.examples.gateway.helper.Constants;
import com.examples.gateway.helper.config.GatewayHelperProperties;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 * 重写JSON类型请求体
 *
 * @author Dai YaLu
 */
@Slf4j
public class ReWriteJsonReqBodyFilter extends AbstractGlobalHelperFilter {

    @Autowired
    private GatewayHelperProperties properties;
    private final AntPathMatcher matcher = new AntPathMatcher();

    @Override
    public Mono<Void> doFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = exchange.getRequest().getURI().getPath();
        String serverName = (String) exchange.getAttributes().get(ServerWebExchangeUtils.GATEWAY_PREDICATE_MATCHED_PATH_ROUTE_ID_ATTR);
        // 请求时间
        exchange.getAttributes().put(Constants.EXAMPLES_GATEWAY_REQ_TIME, LocalDateTime.now());
        if (properties.isReWriteReqJsonBody()) {
            ExamHeader user = exchange.getAttribute(Constants.EXAMPLES_GATEWAY_USER_DETAIL);
            MediaType contentType = request.getHeaders().getContentType();
            if(null==contentType){
                chain.filter(exchange);
            }
            GatewayHelperProperties.ReWriteBody reWriteBody = properties.getReWriteBody();
            if (null != reWriteBody && (reWriteBody.getRequest().stream().anyMatch(t -> matcher.match(t, path))
                    || reWriteBody.getRequest().stream().anyMatch(t -> matcher.match(t, serverName)))) {
                return chain.filter(exchange);
            }
            if (HttpMethod.POST.equals(request.getMethod())&&MediaType.APPLICATION_JSON_VALUE.equals(contentType.getType() + StringPool.SLASH + contentType.getSubtype())) {
                return DataBufferUtils
                        .join(exchange.getRequest().getBody())
                        .map(dataBuffer -> {
                            byte[] bytes = new byte[dataBuffer.readableByteCount()];
                            dataBuffer.read(bytes);
                            DataBufferUtils.release(dataBuffer);
                            return bytes;
                        })
                        .defaultIfEmpty(new byte[0])
                        .flatMap(bytes -> {
                            byte[] body = buildBody(bytes, user);
                            log.info("【网关】组装后的请求参数：{}", new String(body));
                            long contentLength = body.length;
                            ServerHttpRequest newRequest = new ServerHttpRequestDecorator(request.mutate().header(HttpHeaders.CONTENT_LENGTH,Long.toString(contentLength)).build()) {
                                @NotNull
                                @Override
                                public Flux<DataBuffer> getBody() {
                                    DataBufferFactory dataBufferFactory = exchange.getResponse().bufferFactory();
                                    return Flux.just(dataBufferFactory.wrap(body));
                                }
                            };
                            return chain.filter(exchange.mutate().request(newRequest).build());
                        }).doOnError(e -> handleError(exchange, CheckState.EXCEPTION_GATEWAY_HELPER));

//                return Mono.just(exchange.getRequest().getBody()).flatMap(dataBuffer -> {
//                   return chain.filter(exchange);
//                });
//                DataBufferUtils
//                        .join(exchange.getRequest().getBody())
//                        .map(dataBuffer -> {
//                            byte[] bytes = new byte[dataBuffer.readableByteCount()];
//                            dataBuffer.read(bytes);
//                            DataBufferUtils.release(dataBuffer);
//                            return bytes;
//                        }).defaultIfEmpty(new byte[0])
//                        .doOnNext(bytes -> exchange.getAttributes().put(ConstantFilter.CACHED_REQUEST_BODY_OBJECT_KEY, bytes))
//                        .then(chain.filter(exchange));
            }
        }
        return chain.filter(exchange);
    }

    private byte[] buildBody(byte[] body, final ExamHeader header) {
        ExamBaseReq<JSONObject> examBaseReq = new ExamBaseReq<>();
        examBaseReq.setHeader(header);
        if (body.length > 0) {
            JSONObject jsonObject = JSONUtil.parseObj(body);
            examBaseReq.setBody(jsonObject);
        }
        return JSONUtil.toJsonStr(examBaseReq).getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public int getOrder() {
        return 55;
    }
}
